/* Janus Chat - Version 1.0
 * Authors: Matthew Perry
 *          Michael Freid
 *          Marc Latou
 *          Richard Lee
 *
 * The Janus Chat Client is a highly secured
 * peer-to-peer chat client designed to facilitate
 * the transfer of sensitive data or as a communication
 * medium for the extra paranoid
 *
 * This file contains the implementation for the Preferences
 * dialog which allows the user to change his/her moniker */

#include "preferences.h"
#include "../lib/message.h"
#include "ui_preferences.h"
#include <QMessageBox>
#include <QRegExp>

/* Preferences constructor:
 * This just sets up the UI elements for the dialog
 * and makes the current text that of the current monuker */
Preferences::Preferences(const string& moniker, QWidget *parent) :
    QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint),
    ui(new Ui::Preferences)
{
    //Initialize UI elements
    ui->setupUi(this);

    //Set the text to the current moniker
    ui->monikerLine->setText( QString::fromStdString( moniker ) );
}

/* Preferences Destructor:
 * Cleans up the UI elements */
Preferences::~Preferences()
{
    delete ui;
}

/* buttonOK Slot
 * Activated when the OK button is clicked
 * it emits a signal to tell the MainWindow
 * to change the name of the user */
void Preferences::on_buttonOK_clicked()
{
    string newName = ui->monikerLine->text().toStdString();
    if( newName.size() > Message::MONIKER_SIZE )
    {
        //Pop up message box with the errors
        QMessageBox msgBox;
        msgBox.setWindowTitle( "Input Error!" );
        msgBox.setText( "Errors have been found in your input:" );
        msgBox.setInformativeText( "Moniker is too long" );
        msgBox.setIcon( QMessageBox::Critical );
        msgBox.exec();
        return;
    }

    QRegExp moniker( "^([A-Za-z0-9.]*)$" );
    if( !moniker.exactMatch( QString::fromStdString( newName ) ) )
    {
        //Pop up message box with the errors
        QMessageBox msgBox;
        msgBox.setWindowTitle( "Input Error!" );
        msgBox.setText( "Errors have been found in your input:" );
        msgBox.setInformativeText( "Illegal characters in moniker" );
        msgBox.setIcon( QMessageBox::Critical );
        msgBox.exec();
        return;
    }

    emit monikerChange( newName );
    this->close();
}

/* buttonCancel Slot:
 * Activated when the cancel button is clicked
 * it closes this box without saving */
void Preferences::on_buttonCancel_clicked()
{
   this->close();
}
